
const { ccclass, executeInEditMode, property } = cc._decorator;

var PATH = "Common/Shader/";
@ccclass
@executeInEditMode()
class MaterialLoader extends cc.Component {

    _Materials = null;

    loadRes(path: string, cb: Function, type = cc.Material) {
        let url = path;
        if (this._checkIsName) {
            url = PATH + path + "/" + path;
        }
        this._loadRes(url, cb, type);
    }
    _checkIsName(path: string) {
        let paths = path.split("/");
        if (paths.length > 1) {
            return false;
        }
        return true;
    }
    /**
     * 
     * @param path 资源路径
     * @param cb 回调
     * @param type 类型 默认预制体
     */
    _loadRes(path: string, cb: Function, type = cc.Material) {

        // cc.log("已经加载的预制体", this._Materials)

        if (!this._Materials) {
            this._Materials = {};
        }
        if (this._Materials[path]) {
            if (cb) {
                cb(this._Materials[path]);
            }
            return;
        }
        cc.loader.loadRes(
            path,
            type,
            // (completedCount, totalCount, ...item) => {
            //     if (item[0].content)
            //         cc.log("动态读取资源进程:", completedCount, "/", totalCount, item[0].content._name);
            //     else
            //         cc.log("动态读取资源进程:", completedCount, "-----/", totalCount, item);

            // },
            (err, prefab) => {
                if (err) {
                    cc.error("动态加载失败:\nPath:", path, "\nerror:", err)
                    return;
                }
                this._Materials[path] = prefab;
                if (cb) {
                    cb(prefab);
                }
            }
        );
    }

    /**
     * 释放资源
     * 应该不存在需要释放的情况
     * @param path 资源路径 
     * 
     */
    releaseRes(path, type = cc.Material) {
        if (this._Materials && this._Materials[path]) {
            cc.log("释放资源", path)
            cc.loader.releaseRes(path);
            delete this._Materials[path];
        }
    }
    /**
     * 
     */
    releaseAll() {
        if (this._Materials)
            for (const key in this._Materials) {
                this.releaseRes(key);
            }
    }

}
export default new MaterialLoader();